package com.jcxh.sg_exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcxh.sg_exam.pojo.Danxuan;
import com.jcxh.sg_exam.pojo.Duoxuan;
import com.jcxh.sg_exam.pojo.Result;
import com.jcxh.sg_exam.pojo.dto.AddDanxuanDto;
import com.jcxh.sg_exam.pojo.dto.DanxuanDto;
import com.jcxh.sg_exam.service.DanxuanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 鹏少
 * @Date 2024/8/9
 * @Date 9:56
 */
@Api(tags = "单选类接口")
@RestController
@RequestMapping("/admin")
@Slf4j
public class DanxuanController {

    @Autowired
    private DanxuanService danxuanService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("单选类别查询")
    @GetMapping("/getDanXuanType")
    public Result getType() {
        try {
            List<Danxuan> danxuanList = danxuanService.lambdaQuery().getBaseMapper().selectList(null);
            Set<String> collect = danxuanList.stream()
                    .map(Danxuan::getType)
                    .collect(Collectors.toSet());
            return Result.success(collect);
        } catch (Exception e) {
            // 记录日志
            log.error("获取类别时发生异常", e);
            // 返回通用错误信息
            return Result.error("获取类别失败，请稍后再试。");
        }
    }


    @ApiOperation(value = "单选考题查询")
    @GetMapping("/getDanxuan")
    public Result getDanxuan(
            @ApiParam(value = "当前页码", required = true) @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @ApiParam(value = "每页大小(后端默认是10)", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @ApiParam(value = "类别(默认查询全部)") String type,
            @ApiParam(value = "题目") String title) {
        IPage<Danxuan> page = new Page<>(currentPage, pageSize);

        //List<Danxuan> danxuanList  = redisTemplate.opsForList().range("danXuan", 0, -1);

        IPage<Danxuan> danxuanPage = danxuanService.lambdaQuery()
                .eq(type != null, Danxuan::getType, type)
                .like(title != null, Danxuan::getTitle, title)
                .orderByAsc(Danxuan::getId).page(page);
        return Result.success(danxuanPage);

    }


    @ApiOperation(value = "根据单选考题id查询单选题信息")
    @GetMapping("/selectDanxuan")
    public Result selectDanxuan(@ApiParam(value = "单选考题id", required = true) Integer id) {

        Danxuan danxuan = danxuanService.lambdaQuery().eq(Danxuan::getId, id).one();

        return Result.success(danxuan);

    }

    @ApiOperation(value = "单选考题修改保存按钮")
    @PutMapping("/updateDanxuan")
    public Result updateDanxuan(@ApiParam(value = "单选实体类", required = true)
                                @Valid @RequestBody DanxuanDto danxuanDto, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            // 如果有验证错误，返回具体的错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            String errorMessages = fieldErrors.stream()
//                    .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
//                    .collect(Collectors.joining(", "));
            String errorMessages = fieldErrors.stream()
                    .map(fieldError -> fieldError.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return Result.error("验证失败：" + errorMessages);
        }
        boolean flag = danxuanService.lambdaUpdate()
                .set(danxuanDto.getTitle() != null, Danxuan::getTitle, danxuanDto.getTitle())
                .set(danxuanDto.getAnswerA() != null, Danxuan::getAnswerA, danxuanDto.getAnswerA())
                .set(danxuanDto.getAnswerB() != null, Danxuan::getAnswerB, danxuanDto.getAnswerB())
                .set(danxuanDto.getAnswerC() != null, Danxuan::getAnswerC, danxuanDto.getAnswerC())
                .set(danxuanDto.getAnswerD() != null, Danxuan::getAnswerD, danxuanDto.getAnswerD())
                .set(danxuanDto.getType() != null, Danxuan::getType, danxuanDto.getType())
                .set(danxuanDto.getAnswer() != null, Danxuan::getAnswer, danxuanDto.getAnswer())
                .set(danxuanDto.getAnalysis() != null, Danxuan::getAnalysis, danxuanDto.getAnalysis())
                .eq(danxuanDto.getId() != null, Danxuan::getId, danxuanDto.getId()).update();

        // 清空 Redis 中的 List
        redisTemplate.delete("danXuan");

        // 从数据库中获取数据并存入 Redis
        List<Danxuan> danxuanList = danxuanService.lambdaQuery().list();
        redisTemplate.opsForList().rightPushAll("danXuan", danxuanList);
        if (flag) {
            return Result.success("修改成功");

        } else {
            return Result.error("修改失败");
        }

    }

    @ApiOperation(value = "单选考题删除按钮")
    @DeleteMapping("/deleteDanxuan")
    public Result deleteDanxuan(@ApiParam(value = "要删除单选题的id", required = true) @RequestParam(required = true) List<Integer> ids) {

        if (ids.size() == 0) {
            return Result.error("请勾选要删除的考题");
        }
        boolean removeByIds = danxuanService.removeByIds(ids);
        // 清空 Redis 中的 List
        redisTemplate.delete("danXuan");

        // 从数据库中获取数据并存入 Redis
        List<Danxuan> danxuanList = danxuanService.lambdaQuery().list();
        redisTemplate.opsForList().rightPushAll("danXuan", danxuanList);
        if (removeByIds) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }

    }

    @ApiOperation(value = "新增单选考题按钮")
    @PostMapping("/addDanxuan")
    public Result addDanxuan(@ApiParam(value = "新增单选考题dto")
                             @Valid @RequestBody AddDanxuanDto danxuanDto, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            // 如果有验证错误，返回具体的错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            String errorMessages = fieldErrors.stream()
//                    .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
//                    .collect(Collectors.joining(", "));
            String errorMessages = fieldErrors.stream()
                    .map(fieldError -> fieldError.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return Result.error("验证失败：" + errorMessages);
        }
        Danxuan danxuan = new Danxuan();
        BeanUtils.copyProperties(danxuanDto, danxuan);
        danxuan.setOptionA("A");
        danxuan.setOptionB("B");
        danxuan.setOptionC("C");
        danxuan.setOptionD("D");
        boolean save = danxuanService.save(danxuan);
        // 清空 Redis 中的 List
        redisTemplate.delete("danXuan");

        // 从数据库中获取数据并存入 Redis
        List<Danxuan> danxuanList = danxuanService.lambdaQuery().list();
        redisTemplate.opsForList().rightPushAll("danXuan", danxuanList);
        if (save) {
            return Result.success("添加单选考题成功");
        } else {
            return Result.error("添加单选考题失败");
        }

    }


}
